/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @date 2018/6/7 10:48
 * @since 1.0
 */
/**
 * 初始化文章管理详情对话框
 */
var ArticleInfoDlg = {
    articleInfoData : {},
    validateFields: {
        title: {
            validators: {
                notEmpty: {
                    message: '标题不能为空'
                }
            }
        },
        original: {
            validators: {
                notEmpty: {
                    message: '是否原创不能为空'
                }
            }
        },
        tags: {
            validators: {
                notEmpty: {
                    message: '类型不能为空'
                }
            }
        },
        typeId: {
            validators: {
                notEmpty: {
                    message: '分类不能为空'
                }
            }
        },
        status: {
            validators: {
                notEmpty: {
                    message: '状态不能为空'
                }
            }
        },
        comment: {
            validators: {
                notEmpty: {
                    message: '开启评论不能为空'
                }
            }
        },
        description: {
            validators: {
                notEmpty: {
                    message: '描述不能为空'
                }
            }
        },
        keywords: {
            validators: {
                notEmpty: {
                    message: '关键字不能为空'
                }
            }
        }
    }
};

/**
 * 验证数据是否为空
 */
ArticleInfoDlg.validate = function () {
    var isMarkdown = $("#isMarkdown").val();
    if(isMarkdown==0){
        if(Feng.isBlack($("#content").val())){
            Feng.error("文章内容不能为空");
            return false;
        }
    }else{
        if(Feng.isBlack($("##contentMd").val())){
            Feng.error("文章内容不能为空");
            return false;
        }
    }
    $('#publishForm').data("bootstrapValidator").resetForm();
    $('#publishForm').bootstrapValidator('validate');
    return $("#publishForm").data('bootstrapValidator').isValid();
}

/**
 * 清除数据
 */
ArticleInfoDlg.clearData = function() {
    this.articleInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
ArticleInfoDlg.set = function(key, val) {
    return Feng.formSetData(key,val,this,"articleInfoData");
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
ArticleInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
ArticleInfoDlg.close = function() {
    parent.layer.close(window.parent.Article.layerIndex);
}

/**
 * 收集数据
 */
ArticleInfoDlg.collectData = function() {
    this
        .set('id')
        .set('title')
        .set('userId')
        .set('coverImage')
        .set('qrcodePath')
        .set('isMarkdown')
        .set('content')
        .set('contentMd')
        .set('tags')
        .set('top')
        .set('typeId')
        .set('status')
        .set('recommended')
        .set('original')
        .set('description')
        .set('keywords')
        .set('comment')
        .set('createTime')
        .set('updateTime');
}

// 加载所有分类
function loadType(){
    $.ajax({
        type: "post",
        url: "/article/type/list",
        success: function (result) {
            Feng.pass(result,function () {
                var data = '';
                if(data = result.data){
                    var html = '<option value="">选择分类</option>';
                    for(var i=0;i<data.length;i++){
                        html+='<option value="'+data[i].id+'">'+data[i].name+'</option>';
                    }
                    $("select#typeId").html(html);
                }
                $("#refressType").removeClass("fa-spin");
                Feng.showSuccessMessage("分类加载完成");
            })
        },
        error: function () {
            Feng.showErrorMessage("分类加载失败");
        }
    });
}

// 加载所有标签
function loadTag() {
    $.ajax({
        type: "post",
        url: "/article/tags/list",
        success: function (result) {
            Feng.pass(result,function () {
                var data = '';
                if (data = result.data) {
                    var tagHtml = '';
                    for (var i = 0, len = data.length; i < len; i++) {
                        var tag = data[i];
                        tagHtml += '<li>'
                            + '<input type="checkbox" class="square ignore" name="tags" value="' + tag.id + '"> ' + tag.name
                            + '</li>';
                    }
                    $("#tag-list").html(tagHtml);
                    $("input[type=checkbox], input[type=radio]").iCheck({
                        checkboxClass: 'icheckbox_square-green',
                        radioClass: 'iradio_square-green',
                        increaseArea: '20%' // optional
                    });

                    $("i[class*='showContent']").click(function () {
                       if( $("i[class*='showContent']").hasClass("fa-plus-square")){
                           $("i[class*='showContent']").removeClass("fa-plus-square");
                           $("i[class*='showContent']").addClass("fa-minus-square");
                           $("div[class='disable-content']").show();
                       }else{
                           $("i[class*='showContent']").removeClass("fa-minus-square");
                           $("i[class*='showContent']").addClass("fa-plus-square");
                           $("div[class='disable-content']").hide();
                       }
                    });
                }
                $("#refressTag").removeClass("fa-spin");
                Feng.showSuccessMessage("标签加载完成");
            });
        },
        error: function () {
            Feng.showErrorMessage("标签加载失败");
        }
    });
}

function loadArticle() {
     if(articleId){
        $.ajax({
            type: "post",
            url: "/article/article/detail/"+articleId,
            success: function (result) {
                Feng.pass(result,function () {
                    var data = '';
                    if (data = result.data) {
                        var info = result.data;

                        var original = result.original;
                        $("#original").val(original);


                        // 标签
                        var tags = info.tags;

                        for(var i = 0, len = tags.length; i < len ; i ++){
                            var tag = tags[i];
                            $("input[name=tags][value=" + tag.id + "]").iCheck('check');
                        }



                        if(info['coverImage']){
                            $(".coverImage").attr('src', info['coverImageUrl']);
                        }
                        var contentMd = info['contentMd'];
                        if(contentMd){
                            $("#contentMd").val(contentMd);
                            try{
                                if(simplemde){
                                    simplemde.value(contentMd);
                                }
                            }catch (e) {
                                console.log("html编辑器页面没有markdown编辑器");
                            }

                        }
                        var contentHtml = info['content'];
                        if(contentHtml){
                            $("#content").val(contentHtml);
                            try{
                                if(editor){
                                    editor.txt.html(contentHtml);
                                }
                            }catch (e) {
                                console.log("markdown编辑页面没有html编辑器");
                            }
                        }
                        $("#publishForm").find("input[type!=checkbox], select, textarea").each(function () {
                            clearText($(this), this.type, info);
                        });
                    }
                });
            },
            error: function () {
                Feng.showErrorMessage("编辑页加载失败");
            }
        })
    }
}

function clearText($this, type, info){
    var $div = $this.parents(".item");
    if ($div && $div.hasClass("bad")) {
        $div.removeClass("bad");
        $div.find("div.alert").remove();
    }
    if (info) {
        var thisName = $this.attr("name");
        var infoValue = info[thisName];
        if (type == 'radio' || type === 'checkbox') {
            var thisValue = $this.val();
            $this.iCheck((thisValue && thisValue == infoValue+"") ? 'check' : 'uncheck')
        } else if (type.startsWith('select')) {
            if(infoValue == 'true' || infoValue == true) {
                infoValue = 'true';
            } else if(infoValue == 'false' || infoValue == false) {
                infoValue = 'false';
            }
            $this.val(infoValue);
        } else {
            $this.val(infoValue);
        }
    } else {
        if (type === 'radio' || type === 'checkbox') {
            $this.iCheck('uncheck');
        }else{
            $this.val('');
        }
    }
}

$(function() {

    Feng.initValidator("publishForm", ArticleInfoDlg.validateFields);


    $("#refressType").click(function () {
        $(this).addClass("fa-spin");
        loadType();
    });
    $("#refressTag").click(function () {
        $(this).addClass("fa-spin");
        loadTag();
    });

    //当标签和类型都加载完 再去加载文章
    $.when(loadTag(), loadType()).done(function () {
        //所做操作
        loadArticle();
    });

    // 点击保存
    $(".publishBtn").click(function () {
        if (!ArticleInfoDlg.validate()) {
            return;
        }
        $("a[class*='buttonFinish']").addClass("buttonDisabled");
        var url = "";
        if(articleId){
            url = "/article/article/update";
        }else{
            url = "/article/article/add";
        }
        $("#publishForm").ajaxSubmit({
            type: "post",
            url: url,
            success: function (json) {
                Feng.pass(json,function () {
                    //刷新父窗口的url
                    window.parent.Article.table.refresh();
                    ArticleInfoDlg.close();
                })
                $("a[class*='buttonFinish']").removeClass("buttonDisabled");
            },
            error: function (json) {
                $("a[class*='buttonFinish']").removeClass("buttonDisabled");
                if(articleId){
                    Feng.error("编辑文章失败")
                }else{
                    Feng.error("新增文章失败")
                }
            }
        });
    });

    var loadImg = false;
    // 选择图片
    $("#file-upload-btn").click(function () {
        $("#chooseImg").modal('show');
        if(!loadImg){
            // 加载素材库
            $.ajax({
                type: "post",
                url: "/article/article/material",
                success: function (result) {
                    Feng.pass(result,function () {
                        loadImg = true;
                        result.aliossPath = appConfig.aliossPath;
                        var $box = $(".list-material");
                        var tpl = '{{#data}}<li data-imgUrl="{{.}}"><div class="col-md-55"><img class="lazy-img" data-original="{{aliossPath}}{{.}}" alt="image"></div></li>{{/data}}{{^data}}<li>素材库为空</li>{{/data}}';
                        var html = Mustache.render(tpl, result);
                        $box.html(html);
                        $box.find("li").click(function () {
                            $box.find("li").each(function () {
                                $(this).removeClass("active");
                            });
                            var $this = $(this);
                            $this.toggleClass("active");
                            if($this.hasClass("active")){
                                var imgUrl = $this.attr("data-imgUrl");
                                $("#cover-img-input").val(imgUrl);
                                $(".preview img.coverImage").attr("src", appConfig.aliossPath + imgUrl);
                            }
                        });
                        $("img.lazy-img").lazyload({
                            placeholder : appConfig.cmsUrl + "/static/img/loading.gif",
                            effect: "fadeIn",
                            threshold: 100
                        });

                        $("img.lazy-img").trigger("sporty");
                    })
                },
                error: function () {
                    Feng.error("图片库加载失败");
                }
            });
        }
    });


    var coverImage = new $WebUpload({"pictureId":"coverImage","uploadUrl":Feng.ctxPath + '/alioss/upload2Alioss?fileType=COVER_IMAGE'});
    coverImage.init();
    $("input[type='file']").removeAttribute("name");
    // var coverImage1 = new $WebUpload({"pictureId":"coverImage1","uploadUrl":Feng.ctxPath + '/alioss/upload2Alioss?fileType=COVER_IMAGE'});
    // coverImage1.init();


    $(".fa-angle-double-up").click(function () {
        var hidden = $(".custom-container").is(":hidden")
        if(hidden){　　//如果node是隐藏的则显示node元素，否则隐藏
            $(".custom-container").show();
        }else{
            $(".custom-container").hide();
        }

    })
});

